var checkout = {}
checkout.init = function () {
    checkout.chooseAddr();
    checkout.choosePayWay();
    checkout.calculateBill();
    checkout.addNewAddress();
}
checkout.chooseAddr = function () {
    //收货地址展开折叠
    $(document).on('click', '.js-show-more', function (event) {
        if ($('.js-add-list').hasClass('active')) {
            $('.js-add-list li:gt(0)').hide();
            $('.js-add-list').removeClass('active')
        } else {
            $('.js-add-list li:gt(0)').show();
            $('.js-add-list').addClass('active')
        }
    })
    //选择送货地址
    $(document).on('click', '.js-address-item', function (event) {
        var $this = $(event.currentTarget);
        $('.js-address-item.selected').removeClass('selected');
        $($this).addClass('selected');
        $('.js-address').html($($this).find('input').val());
    })
}
//选择支付方式
checkout.choosePayWay = function () {
    $(document).on('click', '.js-pay-way', function (event) {
        $('.js-pay-way.selected').removeClass('selected');
        $(event.currentTarget).addClass('selected');
    })
}
//修改商品数量
checkout.calculateBill = function () {
    //数量加减
    $(document).on('click', '.js-reduce', function (event) {
        var $this = $(event.currentTarget);
        var $num = $this.parent('.count').find('.js-number'), number = parseInt($num.val());
        if (number > 1) {
            number--;
            $num.val(number);
            calculateTotal();
        } else {
            alert2("数量不能再少了哦~");
        }
    })
    $(document).on('click', '.js-add', function (event) {
        var $this = $(event.currentTarget);
        var $num = $this.parent('.count').find('.js-number'), number = parseInt($num.val());
        if (number < 999) {
            number++;
            $num.val(number);
            calculateTotal();
        } else {
            alert2("数量不能再多了哦~");
        }
    })
    $(document).on('change', 'input[name="ticket"]', function (event) {
    	calculateTotal();
    })
    var calculateTotal = function () {
        var list = $('.js-bill-table tr');
        var totalAmount = 0,fare = parseInt($('.js-fare').html());
        $.each(list, function (index, item) {
            var number = $(item).find('.js-number').val();
            var price = $(item).find('.js-price').html();
            var total = parseInt(number) * parseFloat(price);
            totalAmount += total;
            $(item).find('.js-total').html(total.toFixed(2));
        })
        var faxType = $('input[name="ticket"]:checked');
        var faxRate = 1;   //税率
        if(faxType != null && faxType.length > 0 ) {
        	var selectFax = $(faxType[0]).val();
        	if(selectFax == '1') {
        		var faxRate = 1.06;
        	} else if(selectFax == '2') {
        		var faxRate = 1.17;
        	}
        }
        $('.js-bill-amount').html((totalAmount*faxRate).toFixed(2));
        $('.js-pay-amount').html('￥'+(totalAmount*faxRate + fare).toFixed(2));
    }
}
checkout.addNewAddress = function () {
    var model;
    $(document).on('click','.js-newaddress',function () {
        model = $.fn.modal.showModal({
            width:800,
            height:400,
            title: '新增收货地址',
            content:$("#js-add-newaddresss-modal").html()
        })
    })
    $(document).on('click','.js-submit-newaddress',function (evt) {
    	var obj = evt.target;
    	if(submitAddress(obj,model)) {
    		return true;
    	} else {
    		return false;
    	}
    })
}

function submitAddress(obj,model) {
	var form = $(obj).parents("form");
	var info = form.serializeArray();
	var json = {};
	for(var i = 0;i < info.length; i ++ ) {
		var theArr = info[i];
		var key = theArr.name;
		var value = theArr.value;
		json[key] = value;
	}
	var isDefault = $(form.find("input[type='checkbox']")[0]);
	if(isDefault.is(':checked')) {
		json["isDefault"] = true;
	} else {
		json["isDefault"] = false;
	}
	var status = false;
	$.ajax({
		url: "/address/addAddress",
		data:json,
		dataType: "json",
		async:"false",
		type: "post",
		success: function(data) {
			if (data.success) {
				//loading带文字
				layer.msg('添加成功!',{time: 1000, icon:6,shade: [0.5, '#f5f5f5']});
				refreshAddresses();  //刷新地址
				try {
					model.close().remove();//提交数据 关闭窗口
				} catch(e){}
				status = true;
			} else {
				layer.alert(data.msg,{icon:2,skin: 'layer-ext-moon'});
			}
		}
	});
	return status;
}

function refreshAddresses() {   //刷新地址
	$.ajax({
		url: "/address/getAddresses",
		data:{},
		dataType: "json",
		async:"false",
		type: "post",
		success: function(data) {
			if (data.success) {
				//loading带文字
				var addresses = data.addresses;
				var ul = $('#addressList');
				ul.empty();
				for(var i = 0;i < addresses.length;i ++ ) {
					var a = addresses[i];
					var newLi = $('<li></li>');
					var newLabel = $('<label class="address-item js-address-item"><input type="radio" name="address" value="'+a.id+'" /><span>'+a.name+'</span><span>'+a.city.province.name+'</span></label>');
					if(a.isDefault) {
						newLabel.addClass('selected');
					}
					newLi.append(newLabel);
					newLi.append('<span>'+a.name +'   '+a.city.province.name +a.city.name +'   '+a.address +'   '+a.mobile +'</span>');
					ul.append(newLi);
				}
			} else {
				layer.alert(data.msg,{icon:2,skin: 'layer-ext-moon'});
			}
		}
	});
}

var list = {}
list.init = function () {
    $(document).on('click','.js-sl-more',function (event) {
        var target = $('.js-s-brand-list');
        target.toggleClass('expand');
    })
    $(document).on('click','.js-brand-item',function (event) {
        var $this = $(event.currentTarget);
        $this.toggleClass("selected");
        $(document).trigger("update-select-brands");
    })
    $(document).on("update-select-brands",list.updateSelectBrands);
}
list.updateSelectBrands = function () {
    var html = [];
   $.each($(".js-s-brand-list").find(".js-brand-item.selected"),function (idx,item) {
       html.push("<span>",$(item).data("brand-name"),"</span>")
   })
    $(".js-selected-brand-list").html(html.join(""))
}
$(document).ready(function () {
    list.init();
    list.updateSelectBrands();  //初始化选择
})

	var modal = null;
    function orderDesigner(designerId) {
    	$('input[name="designerId"]').val(designerId);
    	modal = $.fn.modal.showModal({
            width:500,
            height:300,
            title: '我要预约',
            content:$("#designOrder_div").html()
            //url:'${ctx}/design/designerOrder?userId='+userId,
        });
    }
    
    function doOrder(obj) {
		var formObj = $(obj).parents("form");
		var info = formObj.serializeArray();
    	var json = {};
    	for(var i = 0;i < info.length; i ++ ) {
    		var theArr = info[i];
    		var key = theArr.name;
    		var value = theArr.value;
    		json[key] = value;
    	} 
    	$.ajax({
    		url: "/design/orderDesigner",
    		data:json,
    		dataType: "json",
    		type: "get",
    		async:"false",
    		success: function(data) {
    			if (data.success) {
    				//loading带文字
    				try {
    					layer.msg('预约成功，请耐心等待!',{time: 1000, icon:6,shade: [0.5, '#f5f5f5']});
    					try {
    						modal.close().remove();//提交数据 关闭窗口
    					} catch(e){}
    				} catch(e) {}
    			} else {
    				try {
    					layer.alert(data.msg,{icon:2,skin: 'layer-ext-moon'});
    				} catch(e){}
    			}
    		}
    	});
    	return false;
	}
    
    function collect(productId) {   //收藏
 	   $.ajax({
 	   		url: "/productCollect/collect",
 	   		data:"productId="+productId,
 	   		dataType: "json",
 	   		type: "get",
 	   		success: function(data) {
 	   			if (data.success) {
 	   				//loading带文字
 	   				layer.msg('收藏成功!',{time: 1000, icon:6,shade: [0.5, '#f5f5f5']});
 	   			} else {
 	   				layer.alert(data.msg,{icon:2,skin: 'layer-ext-moon'});
 	   			}
 	   		}
 	   	});
    }